package com.sn.shop.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sn.shop.enums.ResultStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther sn
 * @date 2018/1/24
 * @description 结果回复工具
 */
public class ResponseUtil {

    /**
     *  以json的形式返回结果
     * @param response
     * @param content 要回复的对象
     */
    public static void responseOutWithJson(HttpServletResponse response,
     String content) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(301);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static String result(ResultStatus status, String msg) {
        return result(status, msg, null);
    }

    /**
     * 格式化返回结果
     * @param status 状态
     * @param msg 信息
     * @param extra 额外参数
     * @return
     */
    public static String result(ResultStatus status, String msg, Map<String, Object> extra) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status.getCode());
        map.put("message", msg);
        if(extra != null)
            map.putAll(extra);
        return JSON.toJSONString(map);
    }

    /**
     * 格式化返回列表结果
     * @param status 状态
     * @param msg 信息
     * @param data 数据
     * @param extra 额外参数
     * @return
     */
    public static String result(ResultStatus status, String msg, List<?> data, Map<String, Object> extra) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status.getCode());
        map.put("message", msg);
        if(extra != null)
            map.putAll(extra);
        map.put("data", data);
        return JSON.toJSONString(map);
    }
}
